package com.apestech.framework.sql.table;

import com.apestech.framework.cache.Cache;
import com.apestech.framework.dictionary.DataDictionary;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.sql.SqlUtil;
import com.apestech.framework.sql.condition.ConditionMap;
import com.apestech.framework.sql.modul.FromList;
import com.apestech.framework.sql.modul.SqlList;
import com.apestech.framework.sql.variable.SqlSection;
import com.apestech.framework.util.ExceptionUtil;
import com.apestech.framework.util.StringFuncUtil;
import com.apestech.framework.xml.sql.modul.SqlRule;

/**
 * @author hup
 * @create 2018-08-30-11:56
 */
public class TableDelete extends SqlUtil {

    private String sql;
    private ConditionMap param;
    private SqlList sqlparam=new SqlList();
    private String schema;

    public TableDelete(ConditionMap param) throws Exception {
        this.param=param;
    }

    public void setSchema(String schema) {
        this.schema = schema;
    }

    public void getTableSql() throws Exception {
        sqlparam=new SqlList();
        //sql= (String) Cache.getKey(param.getCacheKey());
        //if(sql==null){
        sql=getDelete();
        sqlparam=new SqlList();
            //Cache.setKey(param.getCacheKey(), sql);
        //}
        sql=addSql(param.getFromtab(), sql, param, sqlparam, "");
    }

    private String getDelete() throws Exception {
        String tabName="";
        try {
            tabName=param.getFromtab().getTabName();
            if(schema!=null) tabName=schema+"."+tabName;
            Table table=param.getFromtab().getDictTable(tabName);
            SqlRule.Table sqltab=param.getSqlruleTable(tabName);
            String key=param.getSingle().getString("ZTAB_KEY");
            if(key==null){
                if(table.getPkKey()!=null) {
                    key = table.getPkKey().getPkColumn();
                }
            }
            if(sqltab!=null){
                if(sqltab.getWherefield()!=null) {
                    key=sqltab.getWherefield();
                }
            }
            if(param.isTimeControl()){
                if(!"".equals(key)) key=key+";";
                key=key+param.getTimeField();
            }
            String rsql=" DELETE FROM "+tabName+getKeyWhere(key, true, key, param.getTimeField(), param.isTimeControl());
            if(param.getSql()!=null) rsql=rsql+" "+param.getSql();
            sql=rsql;
            return rsql;
        } catch (Exception e) {
            ExceptionUtil.exception(this, "getUpdate", e.getMessage());
        }
        return null;
    }

    public String getSql() {
        return sql;
    }

    public SqlList getSqlparam() {
        return sqlparam;
    }
}
